// ZJX人脸识别API服务
// 连接后端 express 服务的 zjx 路由

// API基础配置
import { ZJX_FACE_API } from '@/config/api'
import axios from 'axios'
import type { AxiosRequestConfig, AxiosResponse } from 'axios'
const API_BASE_URL = ZJX_FACE_API

// 人脸识别结果接口
export interface FaceDetectResult {
  success: boolean
  message: string
  data?: {
    FaceNum: number
    FaceInfos: Array<{
      FaceId: string
      FaceQuality: number
      FaceAttributes?: {
        Age: number
        Gender: string
        Expression: string
        Beauty: number
        Hat: boolean
        Glasses: boolean
        Mask: boolean
      }
      FaceLocation?: {
        X: number
        Y: number
        Width: number
        Height: number
      }
    }>
  }
  error?: string
  suggestions?: string[]
}

export interface FaceLoginResult {
  success: boolean
  message: string
  data?: {
    personId: string
    personName: string
    similarity: number
    faceId: string
    userInfo?: {
      id: string
      name: string
      phone: string
    }
  }
  error?: string
}

export interface FaceRegisterResult {
  success: boolean
  message: string
  data?: {
    faceResult: any
    userData?: {
      id: string
      name: string
      phone: string
      personId: string
    }
  }
  error?: string
}

export interface HealthCheckResult {
  success: boolean
  message: string
  timestamp: string
  config?: {
    region: string
    groupId: string
    similarityThreshold: number
  }
  error?: string
  suggestions?: string[]
}

// ZJX人脸识别API类
class ZJXFaceAPI {
  private baseUrl: string

  constructor() {
    this.baseUrl = API_BASE_URL
  }

  // 通用请求方法
  private async request<T>(endpoint: string, options: AxiosRequestConfig = {}): Promise<T> {
    try {
      const url = `${this.baseUrl}${endpoint}`
      console.log('API请求URL:', url)
      
      const config: AxiosRequestConfig = {
        headers: {
          'Content-Type': 'application/json',
          ...options.headers,
        },
        ...options,
      }

      const response: AxiosResponse<T> = await axios(url, config)

      console.log('API响应状态:', response.status)
      console.log('API响应结果:', response.data)
      
      return response.data
    } catch (error) {
      console.error(`API请求失败 ${endpoint}:`, error)
      if (axios.isAxiosError(error)) {
        const errorMessage = error.response?.data?.message || error.message
        throw new Error(`HTTP error! status: ${error.response?.status}, message: ${errorMessage}`)
      }
      throw error
    }
  }

  // 人脸检测
  async detectFace(imageBase64: string): Promise<FaceDetectResult> {
    try {
      console.log('开始人脸检测...')
      
      // 检查图片大小
      if (imageBase64.length > 10 * 1024 * 1024) {
        return {
          success: false,
          message: '图片大小超过限制（最大10MB）'
        }
      }

      // 处理base64格式，移除data:image/jpeg;base64,前缀
      let processedBase64 = imageBase64;
      if (imageBase64.startsWith('data:image/')) {
        processedBase64 = imageBase64.split(',')[1];
      }

      const result = await this.request<FaceDetectResult>('/detect-face', {
        method: 'POST',
        data: {
          base64: processedBase64
        }
      })

      console.log('人脸检测结果:', result)
      return result
      
    } catch (error) {
      console.error('人脸检测失败:', error)
      return {
        success: false,
        message: '人脸检测服务异常',
        error: error instanceof Error ? error.message : '未知错误'
      }
    }
  }

  // 人脸识别登录
  async faceLogin(imageBase64: string, groupId?: string): Promise<FaceLoginResult> {
    try {
      console.log('开始人脸识别登录...')
      
      // 处理base64格式，移除data:image/jpeg;base64,前缀
      let processedBase64 = imageBase64;
      if (imageBase64.startsWith('data:image/')) {
        processedBase64 = imageBase64.split(',')[1];
      }
      
      const result = await this.request<FaceLoginResult>('/face-login', {
        method: 'POST',
        data: {
          base64: processedBase64,
          groupId: groupId
        }
      })

      console.log('人脸识别登录结果:', result)
      return result
      
    } catch (error) {
      console.error('人脸识别登录失败:', error)
      return {
        success: false,
        message: '人脸识别登录服务异常',
        error: error instanceof Error ? error.message : '未知错误'
      }
    }
  }

  // 人脸注册
  async faceRegister(imageBase64: string, personName: string, personId: string, groupId?: string, phone?: string, password?: string): Promise<FaceRegisterResult> {
    try {
      console.log('开始人脸注册...')
      
      // 处理base64格式，移除data:image/jpeg;base64,前缀
      let processedBase64 = imageBase64;
      if (imageBase64.startsWith('data:image/')) {
        processedBase64 = imageBase64.split(',')[1];
      }
      
      const requestBody: any = {
        base64: processedBase64,
        personName: personName,
        personId: personId,
        groupId: groupId
      }
      
      // 如果提供了手机号和密码，添加到请求中
      if (phone && password) {
        requestBody.phone = phone
        requestBody.password = password
      }
      
      const result = await this.request<FaceRegisterResult>('/face-register', {
        method: 'POST',
        data: requestBody
      })

      console.log('人脸注册结果:', result)
      return result
      
    } catch (error) {
      console.error('人脸注册失败:', error)
      return {
        success: false,
        message: '人脸注册服务异常',
        error: error instanceof Error ? error.message : '未知错误'
      }
    }
  }

  // 健康检查
  async healthCheck(): Promise<HealthCheckResult> {
    try {
      console.log('开始健康检查...')
      
      const result = await this.request<HealthCheckResult>('/face-health', {
        method: 'GET'
      })
      
      console.log('健康检查结果:', result)
      return result
      
    } catch (error) {
      console.error('健康检查失败:', error)
      return {
        success: false,
        message: '健康检查服务异常',
        error: error instanceof Error ? error.message : '未知错误',
        timestamp: new Date().toISOString()
      }
    }
  }

  // 创建人脸库
  async createFaceGroup(): Promise<any> {
    try {
      console.log('创建人脸库...')
      
      const result = await this.request('/create-face-group', {
        method: 'POST',
        data: {}
      })

      return result
      
    } catch (error) {
      console.error('创建人脸库失败:', error)
      throw error
    }
  }

  // 用户注册（传统方式）
  async register(phone: string, password: string, name?: string): Promise<any> {
    try {
      console.log('开始用户注册...')
      
      const result = await this.request('/register', {
        method: 'POST',
        data: {
          phone: phone,
          password: password,
          name: name || ''
        }
      })

      return result
      
    } catch (error) {
      console.error('用户注册失败:', error)
      throw error
    }
  }

  // 发送验证码
  async sendVerificationCode(phone: string): Promise<any> {
    try {
      console.log('发送验证码...')
      
      const result = await this.request('/sendVerificationCode', {
        method: 'POST',
        data: {
          phone: phone
        }
      })

      return result
      
    } catch (error) {
      console.error('发送验证码失败:', error)
      throw error
    }
  }
}

// 创建单例实例
export const zjxFaceAPI = new ZJXFaceAPI()

// 导出便捷方法
export const detectFace = (imageBase64: string) => zjxFaceAPI.detectFace(imageBase64)
export const faceLogin = (imageBase64: string, groupId?: string) => zjxFaceAPI.faceLogin(imageBase64, groupId)
export const faceRegister = (imageBase64: string, personName: string, personId: string, groupId?: string, phone?: string, password?: string) => zjxFaceAPI.faceRegister(imageBase64, personName, personId, groupId, phone, password)
export const healthCheck = () => zjxFaceAPI.healthCheck()
export const createFaceGroup = () => zjxFaceAPI.createFaceGroup()
export const register = (phone: string, password: string, name?: string) => zjxFaceAPI.register(phone, password, name)
export const sendVerificationCode = (phone: string) => zjxFaceAPI.sendVerificationCode(phone)
